package com.xqnode.boot.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.sql.SQLException;


/**
 * 配置多个数据源
 * 默认使用HikariCP
 * 可以使用Druid等多种连接池
 * ...
 */
@Configuration
public class DBConfig {
    /**
     * 基础配置  大多数情况下相同
     */
    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;
    @Value("${spring.datasource.username}")
    private String userName;
    @Value("${spring.datasource.password}")
    private String password;
    @Value("${spring.datasource.url}")

    //url 配置
    private String testUrl;
    @Value("${mytest.url}")
    private String myTestUrl;


    @Bean(name = "testDataSource")
    @Primary
    public DruidDataSource testDataSource() throws SQLException {
        return dataSource(driverClassName, testUrl, userName, password);
    }

    @Bean(name = "mytestDataSource")
    public DataSource mytestDataSource() throws SQLException {
        return dataSource(driverClassName, myTestUrl, userName, password);
    }

    private DruidDataSource dataSource(String driverClassName, String url,
                                       String userName, String password) throws SQLException {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(url);
        druidDataSource.setDriverClassName(driverClassName);
        druidDataSource.setPassword(password);
        druidDataSource.setUsername(userName);
        druidDataSource.setFilters("stat,wall");
        return druidDataSource;
    }

}